package com.fingard.dsp.web;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.web.page.PageBase;
import com.fingard.dsp.web.page.ReceiptDetail;
import com.fingard.dsp.web.page.extsys.notify.BhLife;
import com.fingard.io.FileHelper;
import com.fingard.net.niosocket.HttpNioReceiver;
import com.fingard.net.niosocket.RunCommand;
import com.fingard.text.StringHelper;

import sun.misc.BASE64Decoder;


public class HttpRunnable extends RunCommand{

	private HttpNioReceiver httpReceiver;
	@Override
	public void run() {
		try {
			httpReceiver = (HttpNioReceiver)nioReceiver;
			if (httpReceiver.readedLength == 0) {
	            //F5等设备的监测
				httpReceiver.clientSocketChannel.close();
	            return;
	        }
			StringBuilder tmpRespHead = new StringBuilder();
			String tmpRespBody = "";
			byte[] tmpBytesBody = null;
			String respCharset = httpReceiver.getCharset();
			if("head".equals(httpReceiver.httpMethod)){
				tmpRespHead.append("HTTP/1.1 200 OK\r\n");
        		tmpRespBody = "DSP WEB";
        	}else{
        		/*
        		 * HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Sun, 18 Mar 2018 14:23:37 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: image/jpeg
Content-Length: 53641
Connection: Close
        		 * */
        		HttpContext httpContext = new HttpContext(httpReceiver);
        		httpContext.response.respCharset = respCharset;
        		String page = httpContext.request.getPage().toLowerCase();
        		/*
地址?bank=银行直联代码&receiptno=回单编号&busref=业务参考号&reqbatchno=支付批号&asknumber=支付流水号&directpayway=直联支付方式&abstract=对账码&moneyway=收支方向（1支出，2收入）&isrefund=是否冲正产生（1是，0否）&amount=金额（绝对值）

对于历史明细，传bank=银行直联代码&receiptno=回单编号&busref=业务参考号&abstract=对账码&moneyway=收支方向（1支出，2收入）&amount=金额（绝对值），
如
http://127.0.0.1/receiptdetail?bank=308&receiptno=111222333&busref=83838333&abstract=312020202&moneyway=1&amount=500.45

对于交易单，传bank=银行直联代码&reqbatchno=支付批号&asknumber=支付流水号&directpayway=直联支付方式&abstract=对账码&isrefund=是否冲正产生（1是，0否）&amount=金额（绝对值）
如
http://127.0.0.1/receiptdetail?bank=308&reqbatchno=211222222&asknumber=238388333&directpayway=2&abstract=31488048772&isrefund=0&amount=600.43
        		 * */
        		
        		tmpRespHead.append("HTTP/1.1 200 OK\r\n");
        		tmpRespBody = "Welcome";
        		/*
HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Sun, 18 Mar 2018 14:23:37 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: image/jpeg
Content-Length: 53641
Connection: Close
        		 * */
        		if("/receiptdetail".equals(page) || page.startsWith("/receiptdetail/")){
        			ReceiptDetail recDt = new ReceiptDetail();
        			recDt.httpContext = httpContext;
        			recDt.pageLoad();
        			if(httpContext.response.isRtnBytes){
        				tmpRespHead.append("Server: DSP Web Server\r\nDate: "+Format.toGMT(new Date())+"\r\n");
        				tmpRespHead.append("Content-Type: "+httpContext.response.contentType+"\r\n");
        				tmpBytesBody = httpContext.response.respBytes;
        			}else{
        				httpContext.response.setContentType("htm", "");
        				tmpRespHead.append("Content-Type: "+httpContext.response.contentType+"; charset="+respCharset+"\r\n");
        				tmpRespBody = httpContext.response.respMsg;
        			}
        		}else if("/extsys/notify/bhlife".equalsIgnoreCase(page)){
        			BhLife bh = new BhLife();
        			bh.httpContext = httpContext;
        			bh.pageLoad();
        			if(httpContext.response.isRtnBytes){
        				tmpRespHead.append("Server: DSP Web Server\r\nDate: "+Format.toGMT(new Date())+"\r\n");
        				tmpRespHead.append("Content-Type: "+httpContext.response.contentType+"\r\n");
        				tmpBytesBody = httpContext.response.respBytes;
        			}else{
        				tmpRespBody = httpContext.response.respMsg;
        			}
        		}else if("/favicon.ico".equals(page)){
        			String icoPath = FGBiz.dspCenter.dspSet.webDirPath+File.separator+"favicon.ico";
        			File fileIco = new File(icoPath);
        			if(fileIco.exists()){
        				tmpBytesBody = FileHelper.readFileBytes(icoPath);
        			}else{
        				String favicon_ico = "AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n"+
        						"AAAAAAAAAAAAAAAAAAAAAAAAAAAANZ/MBDagzUQ2oM2ONqDMtDafzbw2oM2cNqDNXjagzRAAAAAA\r\n"+
        						"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANqDNNDagzcg3odD/OaPT/zuk1f87pdX/OqTU/zmi0f83\r\n"+
        						"oc/oNqDNYjagzQIAAAAAAAAAAAAAAAAAAAAANqDNSjii0PQ8ptb/QKnc/0Or3/9FreH/Ra3i/0Ss\r\n"+
        						"4P9Cqt7/P6jZ/zqk0/83oc+MNqDOAgAAAAAAAAAANqDOKDmj0vA/qNr/Ra3h/0mw5/9Nsuz/T7Xv\r\n"+
        						"/1C17/9OtO3/S7Hq/0ev5f9Cqt7/PKbW/zii0GoAAAAAOaPSADqk0rRAqdv/R67k/02z7P9TuPL/\r\n"+
        						"Wbv3/1+++P9gv/j/XL34/1a69f9QtvD/SrHp/0Ss4P89ptfuOqPSFjmj0iw9p9j4Rq7j/0607f9W\r\n"+
        						"uvX/Yr/4/z+k4pY/pOF+P6Thfj2j4XxcuvHsXbz4/1K38v9Ksej/Qqre/zyl1nQ8ptd+Q6zg/02z\r\n"+
        						"6/9Xu/b/Z8P5/3nK9/9DpuE0AAAAAAAAAAAAAAAAb8Px3HHH+P9fv/n/Urfx/0iv5f9Aqdu6OKDc\r\n"+
        						"Rjuj4HI+puRwQqjncEqs53BQr+ZyOqDfFgAAAAAAAAAAAAAAAE2s5GJOreZwR6vncECn5nA8pOFw\r\n"+
        						"OaHeYDl4ClI5fQ6AOYMZgD2HJIBCjCyAR5E0gEqRNlAAAAAAAAAAAEiMMCRLlDmARY8wgD+KKIA7\r\n"+
        						"hR+AOX8UgDl6C2w3fAB4OIUF/zmQHP8+mzL/SKRD/1OuVP9Tp0xsAAAAAAAAAABJlDMeV7FZ+E2q\r\n"+
        						"TP9DoTz/O5Yp/zmLEf84gQC0N3kAJjh+APY5iA3/OZMj/z6bM/9Go0H/Q5UxvDl5DQo6exECPocg\r\n"+
        						"cEqmRf9Dnzr/O5ct/zmOGf84hAX/N3wAbAAAAAA2eQCqOIEC/zmKEP85kiH/PJkv/0GcN/89jSXc\r\n"+
        						"PYoiyEGZM/w/nDT/O5Yq/zmPG/85hgn/N30A6Dd6ABIAAAAANnUAIDZ5AOo4gAH/OIgL/zmOGP85\r\n"+
        						"kiH/OpUn/zuWKf85lCX/OZEe/zmME/84hQf/N30A/DZ4AFwAAAAAAAAAAAAAAAA1cwA+NncA7jd9\r\n"+
        						"AP84ggP/OIYJ/zmIDf85iA7/OYcL/ziFBv84gAH/N3oA/DZ2AHw2dgAAAAAAAAAAAAAAAAAAAAAA\r\n"+
        						"ADVzACg1dAC6NncA/DZ5AP83fAD/N30A/zZ7AP82eQD/NXYA3DV0AFA2dAAAAAAAAAAAAAAAAAAA\r\n"+
        						"AAAAAAAAAAAAAAAANHIAAjVyADI1cgB6NXIAmjVzAJ41cgCINXIASjRyAAgAAAAAAAAAAAAAAAAA\r\n"+
        						"AAAA/D8AAPAPAADgAwAAwAMAAIABAACBwQAAg8AAAP//AACDwQAAg8AAAIHBAACAAQAAwAMAAOAH\r\n"+
        						"AADwDwAA/j8AAA==";//new BASE64Encoder().encode(tmpBytesBody);
        				tmpBytesBody = new BASE64Decoder().decodeBuffer(favicon_ico);
        			}
        			
        			tmpRespHead.append("Content-Type: image/x-icon\r\n");
        		}else if("/refreshdspsystem".equals(page)){
					System.out.println("=====================开始刷新DSP相关配置项=====================");
					//DSPCenter dspCenter=new DSPCenter(FGBiz.DSPHOME);
					//dspCenter.refreshDSPSystem();
					FGBiz.refreshDSPSystem();
					tmpRespHead.append("Content-Type: text/plain; charset="+respCharset+"\r\n");
					tmpRespBody = "刷新完成";
				}else{
					HttpResponse resp = loadPage(httpContext);
					tmpRespHead.append(resp.respHead.toString());
					if(resp.isRtnBytes){
						tmpBytesBody = resp.respBytes;
					}else{
						tmpRespBody = resp.respMsg;
					}
        		}
        		if(StringHelper.hasAnyChar(httpContext.response.contentDisposition)){
        			tmpRespHead.append("Content-Disposition:"+httpContext.response.contentDisposition+"\r\n");
        		}
        	}
			
			if(tmpBytesBody == null){
				tmpBytesBody = tmpRespBody.getBytes(respCharset);
			}
			String tmpStrLen = "" + tmpBytesBody.length;
			
			tmpRespHead.append("Content-Length: " + tmpStrLen + "\r\nConnection: close\r\n\r\n");

            byte[] tmpBytesHead = tmpRespHead.toString().getBytes(respCharset);

            byte[] tmpBytesResp = new byte[tmpBytesHead.length + tmpBytesBody.length];
            ByteBuffer bf = ByteBuffer.wrap(tmpBytesResp);
            bf.put(tmpBytesHead);
            bf.put(tmpBytesBody);
            bf.flip();
            
            httpReceiver.clientSocketChannel.configureBlocking(true);
            httpReceiver.clientSocketChannel.write(bf);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
            try {
				httpReceiver.clientSocketChannel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public HttpResponse loadPage(HttpContext httpContext) throws UnsupportedEncodingException, ReflectiveOperationException, Exception{
		HttpResponse resp = httpContext.response;
		String page = httpContext.request.getPage().toLowerCase();
		String localPagePath = page.replace("/", File.separator);
		if(page.endsWith("/")){
			localPagePath += "index.htm";//默认主页
		}
		
		String fileExt = StringHelper.getFileExt(localPagePath);
		if(StringHelper.isNullOrEmpty(fileExt)){//反射查找page类
			String className = "com.fingard.dsp.web.page."+StringHelper.trimStart(page, "/").replace("/", ".");
			Class<?> pageClass = FGBiz.javaClassMap.getJavaClass(className);
			if (pageClass != null) {
				//客户端请求ID
				String cReqId = httpContext.request.getQryStrValue("reqid");
				PageBase aPage = (PageBase) pageClass.newInstance();
				try{
					httpContext.response.setContentType("txt", "");
					if(StringHelper.hasAnyChar(cReqId)){
						FGBiz.webRuntimeMngr.addReq(cReqId, aPage);
					}
					aPage.httpContext = httpContext;
                	aPage.pageLoad();
                	resp.respHead.append("Server: DSP Web Server\r\nDate: "+Format.toGMT(new Date())+"\r\n");
                	resp.respHead.append("Content-Type: "+httpContext.response.contentType+"; charset="+resp.respCharset+"\r\n");
                	
				}catch(Throwable ex){
					FGBiz.limitMsg.exception(className, ex);
					resp.respMsg = LogHelper.getStackTraceFirstLine(ex);
				}finally{
					if(StringHelper.hasAnyChar(cReqId)){
						FGBiz.webRuntimeMngr.removeReq(cReqId);
					}
				}
			}else{
				resp.respHead.append("Content-Type: text/plain; charset="+resp.respCharset+"\r\n");
				resp.respMsg = "找不到页面"+page;
            }
		}else{
			localPagePath = FGBiz.dspCenter.dspSet.webDirPath+File.separator+StringHelper.trimStartFileSp(localPagePath);
			File pageFile = new File(localPagePath);
			if(pageFile.exists()){
				resp.respHead.append("Server: DSP Web Server\r\nDate: "+Format.toGMT(new Date())+"\r\n");
				resp.respHead.append("Content-Type: "+HttpResponse.getContentType(fileExt, httpContext.request.webBrowser)+"; charset="+resp.respCharset+"\r\n");
				resp.respBytes = FileHelper.readFileBytes(localPagePath);
				resp.isRtnBytes = true;
				//isExistFile = true;
			}else{
				resp.respHead.append("Content-Type: text/plain; charset="+resp.respCharset+"\r\n");
				resp.respMsg = "找不到页面"+page;
			}
		}
		return resp;
	}
	

}
